package com.space.school.controller;

import com.space.school.domain.User;
import com.space.school.service.UserService;
import com.space.school.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "userOperateServlet", value = "/userOperateServlet")
public class UserOperateServlet extends HttpServlet {
    UserService userService = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String userId = req.getParameter("userId");
        User user = new User();
        user.setUserId(Integer.parseInt(userId));
        String operate = req.getParameter("operate");
        if (operate.equals("del")){
            userService.delete(user);
            resp.sendRedirect("/userServlet");
        }else if (operate.equals("update")){
            List<User> users = userService.findById(Integer.parseInt(userId));
            req.setAttribute("user", users.get(0));
            req.getRequestDispatcher("updateUserList.jsp").forward(req, resp);
        }else if (operate.equals("status")){
            String status = req.getParameter("status");
            userService.updateStatus(Integer.parseInt(userId),Integer.parseInt(status));
            resp.sendRedirect("/userServlet");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String userNewPassword = req.getParameter("userNewPassword");
        String userId = req.getParameter("userId");
        String regex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).{6,}$";
        boolean flag = userNewPassword.matches(regex);
        User user = new User();
        if (flag){
            user.setPassWord(userNewPassword);
            user.setUserId(Integer.parseInt(userId));
            userService.update(user);
            resp.sendRedirect("/userServlet");
        }else {
            req.setAttribute("userOperate_msg","密码必须是 6位大写,小写,数字都必须有,你的密码设置太简单了,请重新注册");
            req.getRequestDispatcher("updateUserList.jsp").forward(req, resp);
        }

    }
}
